﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.ApplicationServer.Http.Dispatcher;
using Microsoft.ApplicationServer.Http.Description;
using System.Net.Http;
using ApiPrototype.Models;
using System.Threading.Tasks;

namespace ApiPrototype.Handlers
{
    public class ContentParameterHandler : HttpOperationHandler
    {
        ContentParamAttribute _attr;

        public ContentParameterHandler(ContentParamAttribute attr) : base() { _attr = attr; }

        protected override IEnumerable<HttpParameter> OnGetInputParameters()
        {
            yield return new HttpParameter("request", typeof(HttpRequestMessage));
        }

        protected override IEnumerable<HttpParameter> OnGetOutputParameters()
        {
            yield return new HttpParameter(_attr.ParamName, _attr.ParamType);
        }

        protected override object[] OnHandle(object[] input)
        {
            try
            {

                HttpRequestMessage req = input[0] as HttpRequestMessage;
                ObjectContent oc = new ObjectContent(_attr.ParamType, req.Content);
                oc.Formatters.Insert(0, MvcApplication.jsonNetFormatter);

                Task<Object> t = oc.ReadAsAsync();
                t.Wait();

                return new object[1] { t.Result };
            }
            catch
            {
                throw new ApiException("Error parsing POST data. Expecting " + _attr.ParamType.Name + " as input type.", System.Net.HttpStatusCode.UnsupportedMediaType);
            }
        }
    }
}